package com.zhihaihe.file.advice;

import com.zhihaihe.file.pojo.UserBean;
import com.zhihaihe.file.service.IUserService;
import com.zhihaihe.file.util.AuthConstant;
import com.zhihaihe.file.util.JjwtUtil;
import com.zhihaihe.file.util.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 权限控制面向接口切面
 * @author
 */
@Aspect
@Component
public class AuthenticationAdvice {
    @Autowired
    IUserService userService;
    /**
     * 是否为管理员
     */

    @Before("@annotation(com.zhihaihe.file.annotation.Auth)")
    public void isAdmin(JoinPoint joinPoint ) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        UserBean userBeanByToken = userService.getUserBeanByToken(token);
        List<String> userRole = userService.getUserRole(userBeanByToken.getUserId());
        if (!userRole.contains(AuthConstant.ADMIN)){
            throw new CommonException(ResultCodeEnum.NOT_AUTH_ERROR);
        }

    }
}
